package com.anrong.wulansdk.sdk.utils;

import java.util.Iterator;
import java.util.List;

import com.anrong.gson.Gson;
import com.anrong.gson.GsonBuilder;
import com.anrong.gson.reflect.TypeToken;
import com.anrong.wulansdk.sdk.entity.LocationInfo;
import com.anrong.wulansdk.sdk.interfaces.HttpListener;
import com.anrong.wulansdk.sdk.interfaces.WLHttpUtil;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

/**
 * 定位
 * @author cxy
 *
 */
public class MyLocation{
	
	//定位时间间隔
	private final static long LOCATION_TIME = 10*1000;
	
	
	private static Context context;

	private static LocationManager lm;
	
	private static Double longitude, latitude, altitude;
	
	private static String city = "", province = "", country;
	
	private static MyLocation instance;
	
	private static MyLocationListener listener;
	
	private static Gson gson;


	private static String provider;
	
	private static final String PROVINCE = "wl_province", CITY = "wl_city";
	
//	private MyLocation(Context c){
//		context = c;
//		lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//	}
//	
//	public static MyLocation getInstance(Context c){
//		if (instance == null) {
//			synchronized (MyLocation.class) {
//				instance = new MyLocation(c);
//			}
//		}
//		return instance;
//	}
	
	public static void init(Context c){
		context = c;
		
		if (!CheckPermission()) {
			return;
		}
		
		lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		registenerLocationChangeListener();
	}
	
	/**
	 * 检查权限
	 */
	@TargetApi(23)
	private static boolean CheckPermission() {
		String[] permissions = {
				Manifest.permission.ACCESS_FINE_LOCATION,
				Manifest.permission.ACCESS_COARSE_LOCATION};

		if(Build.VERSION.SDK_INT >= 23){//判断当前系统的版本  
			for (String permission : permissions) {
				int location = context.checkSelfPermission(permission);//获取系统是否被授予该种权限  
				if(location != PackageManager.PERMISSION_GRANTED){
					MyLogcat.log("获取地理位置权限失败: "+permission);
					return false;
				}
			}
		}else {
			return true;
		}
		return true;
	}


	/**
	 * 注册监听
	 */
	public static void registenerLocationChangeListener(){
		
		List<String> providers = lm.getProviders(true);
		
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			
			lm.addGpsStatusListener(new Listener() {
				@Override
				public void onGpsStatusChanged(int event) {
					if(event==GpsStatus.GPS_EVENT_FIRST_FIX){  
			            //第一次定位  
			        }else if(event==GpsStatus.GPS_EVENT_SATELLITE_STATUS){  
			            //卫星状态改变  
			            GpsStatus gpsStatus= lm.getGpsStatus(null); // 取当前状态  
			            int maxSatellites = gpsStatus.getMaxSatellites(); //获取卫星颗数的默认最大值  
			            Iterator<GpsSatellite> it = gpsStatus.getSatellites().iterator();//创建一个迭代器保存所有卫星  
			            int count = 0;    
			            while (it.hasNext() && count <= maxSatellites) {    
			                count++;   
			                GpsSatellite s = it.next();  
			            }    
			            System.out.println("搜索到："+count+"颗卫星");  
			        }else if(event==GpsStatus.GPS_EVENT_STARTED){
			        	provider = LocationManager.GPS_PROVIDER;
			            //定位启动
			        	requestLocation(provider);
			        }else if(event==GpsStatus.GPS_EVENT_STOPPED){
			            //定位结束 
			        }
				}
			});
			
			
		}
		
		if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
			requestLocation(provider);
		}else {
			//没有provider提供, 请打开gps开关
			return;
		}
		
//		String provider = getProvider();
//		lm.requestLocationUpdates(provider, 2000, 0, getListener());
		updateWithLocation(lm.getLastKnownLocation(provider));
	}
	
	
	
	/**
	 * 获取经度
	 * @return
	 */
	public static String getLongitude(){
		return String.valueOf(longitude);
	}
	/**
	 * 获取纬度
	 * @return
	 */
	public static  String getLatitude(){
		return String.valueOf(latitude);
	}
	/**
	 * 获取高度
	 * @return
	 */
	public static  String getAltitude(){
		return String.valueOf(altitude);
	}
	
	public static String getProvince(){
		return "".equals(province) ? PreferenceUtil.getString(context, PROVINCE):province;
	}
	
	public static String getCity(){
		return "".equals(city) ? PreferenceUtil.getString(context, CITY):city;
	}
	

	/**
	 * 获取provider
	 * @return
	 */
	private String getProvider() {
		  
        // 构建位置查询条件  
        Criteria criteria = new Criteria();  
  
        // 查询精度：高  
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);  
  
        // 是否查询海拨
        criteria.setAltitudeRequired(true);  
  
        // 是否查询方位角 : 否  
        criteria.setBearingRequired(false);  
  
        // 是否允许付费：是  
        criteria.setCostAllowed(false);  
  
        // 电量要求：低  
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
        
//        criteria.setSpeedRequired(false); // 对速度是否关注
  
        MyLogcat.log("Current LocationManager:"+lm.getBestProvider(criteria, true));
        
        // 获取最好的定位方式
        return lm.getBestProvider(criteria, true);  // true 代表从打开的设备中查找
  
    }  
	
	/**
	 * 获取监听
	 * @return
	 */
	protected static LocationListener getListener() {
		if (listener == null) {
			listener = new MyLocationListener();
		}
		return listener;
	}
	

	private static void updateWithLocation(Location location) {
		if (location == null) {
			return;
		}
		
		//位置发生改变时调用   
		longitude = location.getLongitude();//116.363324
		latitude = location.getLatitude();//39.986394
		altitude = location.getAltitude();
		
		MyLogcat.log("*********************" + longitude + "," + latitude +","+ altitude + "**************"+province+","+city+"**********");
		
		getLocationInfo(location.getLatitude(), location.getLongitude());
		
	}
	
	
	/**
	 * 自定义位置监听
	 * @author cxy
	 *
	 */
	static class MyLocationListener implements LocationListener{

		@Override
		public void onLocationChanged(Location location) {
			Log.i("location", "onLocationChanged");//39.792449,  116.579626
			updateWithLocation(location);
		}
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			//状态改变时调用
			Log.i("location", "onStatusChanged");
		}

		@Override
		public void onProviderEnabled(String provider) {
			//provider启用时调用
			Log.i("location", "onProviderEnabled");
		}

		@Override
		public void onProviderDisabled(String provider) {
			//provider失效时调用
			Log.i("location", "onProviderDisabled");
			switch (provider) {
			case LocationManager.NETWORK_PROVIDER:
				requestLocation(LocationManager.GPS_PROVIDER);
				break;
			case LocationManager.GPS_PROVIDER:
				requestLocation(LocationManager.NETWORK_PROVIDER);
				break;

			default:
				break;
			}
		}
		
	}
	
	/**
	 * 请求定位更新
	 * @param provider
	 */
	private static void requestLocation(String provider){
		lm.requestLocationUpdates(provider, LOCATION_TIME, 1, getListener());
	}
	
	
	
	/**********取消监听**********/
	public static void unRegisterLocationChangeListener(){
		lm.removeUpdates(getListener());
	}
	
	/**
	 * 坐标换位置信息
	 * @param latitude
	 * @param longitude
	 */
	private static void getLocationInfo(double latitude, double longitude){
//		WLHttpUtil.get(DataURL.locaiton(latitude, longitude), new StringCallback() {
//			
//			@Override
//			public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
//				if (gson == null) {
//					gson = new GsonBuilder().create();
//				}
//				LocationInfo info = gson.fromJson(arg1, new TypeToken<LocationInfo>(){}.getType());
//				if (info == null || !"OK".equals(info.getStatus())) {
//					return;
//				}
//				province = info.getResult().getAddressComponent().getProvince();
//				city = info.getResult().getAddressComponent().getCity();
//				
//				PreferenceUtil.putString(context, PROVINCE, province);
//				PreferenceUtil.putString(context, CITY, city);
//				
//			}
//			
//			@Override
//			public void onError(boolean isFromCache, Call call, Response response, Exception e) {
//				Log.e("wulan", e.getMessage());
//			}
//		});
		
		WLHttpUtil.getLocationInfo(latitude, longitude, new HttpListener() {
			
			@Override
			public void onSuccess(String result) {
				if (gson == null) {
					gson = new GsonBuilder().create();
				}
				LocationInfo info = gson.fromJson(result, new TypeToken<LocationInfo>(){}.getType());
				if (info == null || !"OK".equals(info.getStatus())) {
					return;
				}
				province = info.getResult().getAddressComponent().getProvince();
				city = info.getResult().getAddressComponent().getCity();
				
				MyLogcat.log(province+", "+city);
				
				PreferenceUtil.putString(context, PROVINCE, province);
				PreferenceUtil.putString(context, CITY, city);
			}
			
			@Override
			public void onFail(Exception e) {
				MyLogcat.e(e.getMessage());
			}
		});
		
	}
	
}
